package com.example.mobwe_project;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.app.Application;
import android.util.Log;

public class ZipReader extends Application {
	
	private File zip;
	
	public ZipReader(){		
	}
	
	public ZipReader( String filePath ){
		this.zip = new File( filePath );
	}
	
	public Boolean open( String filePath ){
		Log.d("ZipReader", "Opening a zip file");
		File file = new File( filePath );
		if( file.exists() ){
			this.zip = file;
			Log.d("ZipReader", "Opening succeed");
			return true;
		}else{
			Log.d("ZipReader", "Opening failed");
			return false;
		}
	}
	
	public Boolean extractTo( String extractPath ){		
		Log.d("ZipReader","Starting to read the zip file");
		try {
			Log.d("ZipReader","Checking if the extract folder exists");
	        File extractFolder = new File( extractPath );
	        if( !extractFolder.exists() ){
				Log.d("ZipReader","It doesn't exist. Trying to create one");
	        	if( !extractFolder.mkdir() ){
	        		Log.d("ZipReader","Creating wasn't succesful");
	        		return false;
	        	}
	        }	        

	        ZipEntry entry;      
	        int extracted = 0;
	        
	        Log.d("ZipReader","Creating the input stream");
	        FileInputStream inStream = new FileInputStream( this.zip );
	        Log.d("ZipReader","Creating the buffered input stream");
	        ZipInputStream zipStream = new ZipInputStream( new BufferedInputStream( inStream ) );
	        Log.d("ZipReader","Starting to process the input stream");
	        
	        while((entry = zipStream.getNextEntry()) != null) {
	            if (entry.isDirectory()) {
	            	Log.d("ZipReader","Extracting a folder " + extractPath + "/" + entry.getName());
	                new File( extractPath + "/" + entry.getName() ).mkdirs();
	            } else {
	            	Log.d("ZipReader","Extracting a file " + extractPath + "/" + entry.getName());
	                FileOutputStream outStream = new FileOutputStream( extractPath + "/" + entry.getName());
	                for (int c = zipStream.read(); c != -1; c = zipStream.read()) {
	                    outStream.write(c);
	                }
	                zipStream.closeEntry();
	                outStream.close();
	                extracted ++;
	            }
	        }
	        Log.d("ZipReader", "Items extracted = " + extracted + ". Extracting process was succesful");
	        zipStream.close();
	        inStream.close();
	        return true;
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
	        Log.d("ZipReader", e.toString());
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
        return false;
	}
}